package com.gzc.just.play.last.war.allinone.robot;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

import com.gzc.just.play.last.war.robotclient.RobotClientProperties;
import com.gzc.just.play.last.war.robotclient.RobotClientManager;

/**
 * All-in-One模式机器人客户端配置和集成
 * 通过配置开关控制是否启动机器人客户端
 */
@Configuration
public class AllInOneRobotConfig implements ApplicationListener<ApplicationReadyEvent> {
    private static final Logger log = LoggerFactory.getLogger(AllInOneRobotConfig.class);
    
    @Autowired
    private Environment environment;
    
    @Autowired(required = false)
    private RobotClientManager robotManager;
    
    @Autowired(required = false)
    private RobotClientProperties robotClientProperties;
    
    @Override
    public void onApplicationEvent(ApplicationReadyEvent event) {
        if (robotClientProperties == null || !robotClientProperties.isEnabled()) {
            log.info("Robot client is disabled, skipping initialization");
            return;
        }
        
        if (robotManager == null) {
            log.error("RobotManager bean not found, Robot client cannot start");
            return;
        }
        
        // 等待其他服务器完全启动
        int startupDelay = robotClientProperties.getStartupDelay();
        log.info("Robot client is enabled, will start after {}ms delay", startupDelay);
        
        try {
            Thread.sleep(startupDelay);
            
            log.info("Starting RobotManager with config: maxRobots={}, initialCount={}", 
                    robotClientProperties.getMaxRobots(), 
                    robotClientProperties.getInitialCount());
            
            robotManager.initialize();
            
            // 创建初始机器人
            if (robotClientProperties.getInitialCount() > 0) {
                createInitialRobots();
            }
            
            log.info("Robot client integration completed successfully");
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            log.error("Robot client startup interrupted", e);
        } catch (Exception e) {
            log.error("Failed to initialize robot client", e);
        }
    }

    private void createInitialRobots() {
        try {
            int count = robotClientProperties.getInitialCount();
            long startId = robotClientProperties.getInitialRobotId();
            
            com.gzc.just.play.last.war.robotclient.RobotClientConfig config = 
                new com.gzc.just.play.last.war.robotclient.RobotClientConfig(
                    startId,
                    robotClientProperties.getRobotDefault().getUsernamePrefix(),
                    robotClientProperties.getRobotDefault().getPassword(),
                    robotClientProperties.getRobotDefault().getNicknamePrefix()
                );
                
            // 设置服务器信息
            config.setLoginServerHost(robotClientProperties.getLoginServer().getHost());
            config.setLoginServerPort(robotClientProperties.getLoginServer().getPort());
            config.setGateServerHost(robotClientProperties.getGateServer().getHost());
            config.setGateServerPort(robotClientProperties.getGateServer().getPort());
            
            // 设置其他属性
            config.setSex(robotClientProperties.getRobotDefault().getSex());
            config.setHeaderId(robotClientProperties.getRobotDefault().getHeaderId());
            config.setPlatformId(robotClientProperties.getRobotDefault().getPlatformId());
            
            robotManager.createRobots(count, config);
        } catch (Exception e) {
            log.error("Failed to create initial robots", e);
        }
    }
}